package org.abc.fund.service.factorService;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.abc.fund.entity.factorEntity.*;
import org.abc.fund.repository.factorRepository.FactorRepository;
import org.abc.fund.repository.factorRepository.StyleFactorComponentRepository;
import org.abc.fund.repository.factorRepository.StyleFactorDataRepository;
import org.abc.fund.repository.factorRepository.StyleFactorRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 风格因子管理服务
 */
@Service
@RequiredArgsConstructor
@Transactional
public class StyleFactorService {
    private static final Logger log = LoggerFactory.getLogger(StyleFactorService.class);
    private final StyleFactorRepository styleFactorRepository;
    private final StyleFactorComponentRepository componentRepository;
    private final FactorRepository factorRepository;
    private final StyleFactorDataRepository styleFactorDataRepository;
    private final DataSourceIngestionHistoryService dataSourceIngestionHistoryService;
    private final StyleFactorComponentRepository styleFactorComponentRepository;
    private final FactorService factorService;

    private static final Map<String, String> FACTOR_NAME_MAP = new HashMap<>();
    static {
        FACTOR_NAME_MAP.put("简单收益率因子", "简单收益率因子");
        FACTOR_NAME_MAP.put("annual_return", "年化收益率因子");
        FACTOR_NAME_MAP.put("年化收益率", "年化收益率因子");
        FACTOR_NAME_MAP.put("年化收益率因子", "年化收益率因子");
        FACTOR_NAME_MAP.put("log_return", "对数收益率因子");
        FACTOR_NAME_MAP.put("对数收益率", "对数收益率因子");
        FACTOR_NAME_MAP.put("对数收益率因子", "对数收益率因子");
        FACTOR_NAME_MAP.put("volatility", "波动率因子");
        FACTOR_NAME_MAP.put("波动率", "波动率因子");
        FACTOR_NAME_MAP.put("波动率因子", "波动率因子");
        FACTOR_NAME_MAP.put("sharpe", "夏普比率因子");
        FACTOR_NAME_MAP.put("夏普比率", "夏普比率因子");
        FACTOR_NAME_MAP.put("夏普比率因子", "夏普比率因子");
        FACTOR_NAME_MAP.put("max_drawdown", "最大回撤因子");
        FACTOR_NAME_MAP.put("最大回撤", "最大回撤因子");
        FACTOR_NAME_MAP.put("最大回撤因子", "最大回撤因子");
        FACTOR_NAME_MAP.put("downside_risk", "下行风险因子");
        FACTOR_NAME_MAP.put("下行风险", "下行风险因子");
        FACTOR_NAME_MAP.put("下行风险因子", "下行风险因子");
        FACTOR_NAME_MAP.put("rsi", "相对强弱指数因子");
        FACTOR_NAME_MAP.put("相对强弱指数", "相对强弱指数因子");
        FACTOR_NAME_MAP.put("相对强弱指数因子", "相对强弱指数因子");
        FACTOR_NAME_MAP.put("ma", "移动平均值因子");
        FACTOR_NAME_MAP.put("移动平均", "移动平均值因子");
        FACTOR_NAME_MAP.put("移动平均值因子", "移动平均值因子");
        FACTOR_NAME_MAP.put("申购开放频率", "申购开放频率因子");
        FACTOR_NAME_MAP.put("申购开放频率因子", "申购开放频率因子");
        FACTOR_NAME_MAP.put("赎回开放频率", "赎回开放频率因子");
        FACTOR_NAME_MAP.put("赎回开放频率因子", "赎回开放频率因子");
    }

    /**
     * 创建风格因子
     */
    @CacheEvict(value = "styleFactorCache", allEntries = true)
    public StyleFactor createStyleFactor(StyleFactorDto dto) throws JsonProcessingException {
        try {
            if (styleFactorRepository.existsByFactorCode(dto.getFactorCode())) {
                throw new IllegalArgumentException("风格因子代码已存在: " + dto.getFactorCode());
            }
            
            // 创建风格因子
            StyleFactor styleFactor = new StyleFactor();
            styleFactor.setFactorCode(dto.getFactorCode());
            styleFactor.setFactorName(dto.getName());
            styleFactor.setDescription(dto.getDescription());
            styleFactor.setStyleType(dto.getFactorType());
            styleFactor.setFormula(dto.getAlgorithmParams() + dto.getWeightsConfig());
            styleFactor.setFrequency(StyleFactor.CalculationFrequency.MONTHLY); // 默认月频
            styleFactor.setEnabled(dto.isEnabled());
            styleFactor.setCreateTime(LocalDateTime.now());
            styleFactor.setUpdateTime(LocalDateTime.now());
            
            // 先保存风格因子
            StyleFactor savedStyleFactor = styleFactorRepository.save(styleFactor);
            
            // 解析新的权重配置结构
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(dto.getWeightsConfig());
            
            // 支持新的多因子配置结构
            List<BigDecimal> weights = new ArrayList<>();
            List<String> operators = new ArrayList<>();
            
            // 尝试从新的结构获取数据
            JsonNode weightsNode = rootNode.get("weights");
            JsonNode operatorsNode = rootNode.get("operators");
            JsonNode factorsNode = rootNode.get("factors");
            
            if (weightsNode != null && weightsNode.isArray()) {
                for (int i = 0; i < weightsNode.size(); i++) {
                    double weight = weightsNode.get(i).asDouble();
                    weights.add(BigDecimal.valueOf(weight));
                }
            }
            
            if (operatorsNode != null && operatorsNode.isArray()) {
                for (int i = 0; i < operatorsNode.size(); i++) {
                    operators.add(operatorsNode.get(i).asText());
                }
            }
            
            // 如果从factors节点获取数据
            if (factorsNode != null && factorsNode.isArray()) {
                for (int i = 0; i < factorsNode.size(); i++) {
                    JsonNode factorNode = factorsNode.get(i);
                    if (factorNode.has("weight")) {
                        double weight = factorNode.get("weight").asDouble();
                        weights.add(BigDecimal.valueOf(weight));
                    }
                    if (factorNode.has("operator")) {
                        operators.add(factorNode.get("operator").asText());
                    }
                }
            }
            
            // 如果没有获取到权重，使用默认权重
            if (weights.isEmpty()) {
                for (int i = 0; i < dto.getBaseFactors().size(); i++) {
                    weights.add(BigDecimal.valueOf(1.0 / dto.getBaseFactors().size()));
                }
            }
            
            // 如果没有获取到算子，使用默认算子
            if (operators.isEmpty()) {
                for (int i = 0; i < dto.getBaseFactors().size(); i++) {
                    operators.add("ADD");
                }
            }
            
            // 创建风格因子组件
            List<StyleFactorComponent> styleFactorComponents = new ArrayList<>();
            for (int i = 0; i < dto.getBaseFactors().size(); i++) {
                StyleFactorComponent component = new StyleFactorComponent();
                component.setStyleFactor(savedStyleFactor);
                component.setInputFactor(dto.getBaseFactors().get(i));
                component.setWeight(i < weights.size() ? weights.get(i) : BigDecimal.valueOf(1.0 / dto.getBaseFactors().size()));
                component.setOperationType(i < operators.size() ? OperationType.valueOf(operators.get(i)) : OperationType.valueOf(dto.getAlgorithm()));
                styleFactorComponents.add(component);
            }
            
            // 保存组件
            if (!styleFactorComponents.isEmpty()) {
                componentRepository.saveAll(styleFactorComponents);
            }
            
            return savedStyleFactor;
        } catch (Exception e) {
            log.error("创建风格因子失败: {}", e.getMessage(), e);
            throw new RuntimeException("创建风格因子失败: " + e.getMessage(), e);
        }
    }

    /**
     * 更新风格因子
     */
    @CacheEvict(value = "styleFactorCache", allEntries = true)
    public StyleFactor updateStyleFactor(String factorCode, StyleFactorDto dto) throws JsonProcessingException {
        try {
            StyleFactor existing = styleFactorRepository.findByFactorCode(factorCode)
                    .orElseThrow(() -> new IllegalArgumentException("风格因子不存在: " + factorCode));
            
            // 检查因子代码是否被其他记录使用
            if (!existing.getFactorCode().equals(dto.getFactorCode()) &&
                    styleFactorRepository.existsByFactorCode(dto.getFactorCode())) {
                throw new IllegalArgumentException("风格因子代码已存在: " + dto.getFactorCode());
            }
            
            // 更新风格因子基本信息
            existing.setFactorCode(dto.getFactorCode());
            existing.setFactorName(dto.getName());
            existing.setDescription(dto.getDescription());
            existing.setStyleType(dto.getFactorType());
            existing.setFormula(dto.getAlgorithmParams() + dto.getWeightsConfig());
            existing.setEnabled(dto.isEnabled());
            existing.setUpdateTime(LocalDateTime.now());
            
            // 保存更新的风格因子
            StyleFactor updatedStyleFactor = styleFactorRepository.save(existing);
            
            // 删除旧的组件
            componentRepository.deleteByStyleFactor(existing);
            
            // 解析新的权重配置结构
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(dto.getWeightsConfig());
            
            // 支持新的多因子配置结构
            List<BigDecimal> weights = new ArrayList<>();
            List<String> operators = new ArrayList<>();
            
            // 尝试从新的结构获取数据
            JsonNode weightsNode = rootNode.get("weights");
            JsonNode operatorsNode = rootNode.get("operators");
            JsonNode factorsNode = rootNode.get("factors");
            
            if (weightsNode != null && weightsNode.isArray()) {
                for (int i = 0; i < weightsNode.size(); i++) {
                    double weight = weightsNode.get(i).asDouble();
                    weights.add(BigDecimal.valueOf(weight));
                }
            }
            
            if (operatorsNode != null && operatorsNode.isArray()) {
                for (int i = 0; i < operatorsNode.size(); i++) {
                    operators.add(operatorsNode.get(i).asText());
                }
            }
            
            // 如果从factors节点获取数据
            if (factorsNode != null && factorsNode.isArray()) {
                for (int i = 0; i < factorsNode.size(); i++) {
                    JsonNode factorNode = factorsNode.get(i);
                    if (factorNode.has("weight")) {
                        double weight = factorNode.get("weight").asDouble();
                        weights.add(BigDecimal.valueOf(weight));
                    }
                    if (factorNode.has("operator")) {
                        operators.add(factorNode.get("operator").asText());
                    }
                }
            }
            
            // 如果没有获取到权重，使用默认权重
            if (weights.isEmpty()) {
                for (int i = 0; i < dto.getBaseFactors().size(); i++) {
                    weights.add(BigDecimal.valueOf(1.0 / dto.getBaseFactors().size()));
                }
            }
            
            // 如果没有获取到算子，使用默认算子
            if (operators.isEmpty()) {
                for (int i = 0; i < dto.getBaseFactors().size(); i++) {
                    operators.add("ADD");
                }
            }
            
            // 创建新的风格因子组件
            List<StyleFactorComponent> styleFactorComponents = new ArrayList<>();
            for (int i = 0; i < dto.getBaseFactors().size(); i++) {
                StyleFactorComponent component = new StyleFactorComponent();
                component.setStyleFactor(updatedStyleFactor);
                component.setInputFactor(dto.getBaseFactors().get(i));
                component.setWeight(i < weights.size() ? weights.get(i) : BigDecimal.valueOf(1.0 / dto.getBaseFactors().size()));
                component.setOperationType(i < operators.size() ? OperationType.valueOf(operators.get(i)) : OperationType.valueOf(dto.getAlgorithm()));
                styleFactorComponents.add(component);
            }
            
            // 保存新组件
            if (!styleFactorComponents.isEmpty()) {
                componentRepository.saveAll(styleFactorComponents);
            }
            
            return updatedStyleFactor;
        } catch (Exception e) {
            log.error("更新风格因子失败: {}", e.getMessage(), e);
            throw new RuntimeException("更新风格因子失败: " + e.getMessage(), e);
        }
    }

    /**
     * 删除风格因子
     */
    @CacheEvict(value = "styleFactorCache", allEntries = true)
    public void deleteStyleFactor(Long id) {
        StyleFactor styleFactor = styleFactorRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("风格因子不存在: " + id));
        styleFactorRepository.delete(styleFactor);
    }

    /**
     * 根据ID查找风格因子
     */
    @Cacheable(value = "styleFactorCache", key = "#id")
    @Transactional(readOnly = true)
    public Optional<StyleFactor> findById(Long id) {
        return styleFactorRepository.findById(id);
    }

    /**
     * 分页查询风格因子
     */
    @Transactional(readOnly = true)
    public Page<StyleFactor> findStyleFactors(String styleType, Boolean enabled, Pageable pageable) {
        if (styleType != null && enabled != null) {
            return styleFactorRepository.findByStyleTypeAndEnabled(styleType, enabled, pageable);
        } else if (styleType != null) {
            return styleFactorRepository.findByStyleType(styleType, pageable);
        } else if (enabled != null) {
            return styleFactorRepository.findByEnabled(enabled, pageable);
        } else {
            return styleFactorRepository.findAll(pageable);
        }
    }

    /**
     * 获取所有风格因子（支持过滤）
     */
    @Transactional(readOnly = true)
    public List<StyleFactor> getAllStyleFactors(Boolean enabled) {
        if (enabled != null) {
            return styleFactorRepository.findByEnabled(enabled);
        }else {
            return styleFactorRepository.findAll();
        }
    }

    /**
     * 模糊查询因子名称
     */
    @Transactional(readOnly = true)
    public List<StyleFactor> findByFactorNameContaining(String name) {
        return styleFactorRepository.findByFactorNameContaining(name);
    }

    /**
     * 模糊查询因子代码
     */
    @Transactional(readOnly = true)
    public List<StyleFactor> findByFactorCodeContaining(String code) {
        return styleFactorRepository.findByFactorCodeContaining(code);
    }

    /**
     * 多条件搜索风格因子
     */
    @Transactional(readOnly = true)
    public Page<StyleFactor> searchStyleFactors(String name, String code, StyleFactor.StyleType styleType, 
                                               String algorithm, Boolean enabled, Pageable pageable) {
        return styleFactorRepository.searchStyleFactors(name, code, styleType, algorithm, enabled, pageable);
    }

    /**
     * 启用/禁用风格因子
     */
    @CacheEvict(value = "styleFactorCache", allEntries = true)
    public StyleFactor toggleStyleFactorStatus(Long id, Boolean enabled) {
        StyleFactor styleFactor = styleFactorRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("风格因子不存在: " + id));
        styleFactor.setEnabled(enabled);
        styleFactor.setUpdateTime(LocalDateTime.now());
        return styleFactorRepository.save(styleFactor);
    }

    /**
     * 计算风格因子值
     */
    public BigDecimal calculateStyleFactorValue(String styleFactorCode, String fundCode) {
        StyleFactor styleFactor = styleFactorRepository.findByFactorCode(styleFactorCode)
                .orElseThrow(() -> new IllegalArgumentException("风格因子不存在: " + styleFactorCode));

        if (!styleFactor.getEnabled()) {
            throw new IllegalArgumentException("风格因子已禁用: " + styleFactorCode);
        }
        
        // 获取输入因子组件
        Optional<StyleFactor> styleFactorOptional = styleFactorRepository.findByFactorCode(styleFactorCode);
        List<StyleFactorComponent> components = styleFactorOptional.get().getComponents();
        if (components.isEmpty()) {
            throw new IllegalArgumentException("风格因子没有配置输入组件: " + styleFactorCode);
        }
        
        BigDecimal result = BigDecimal.ZERO;
        boolean hasValidData = false;
        LocalDate today = LocalDate.now();
        LocalDate oneMonthAgo = today.minusMonths(1);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String todayFormatted = today.format(formatter);
        String oneMonthAgoFormatted = oneMonthAgo.format(formatter);
        List<Double> simpleFactor = dataSourceIngestionHistoryService.getShowData(fundCode, oneMonthAgoFormatted, todayFormatted);
        
        List<String> missingFactors = new ArrayList<>();
        // 根据风格类型和公式计算风格因子值
        for (StyleFactorComponent component : components) {
            String rawFactorName = component.getInputFactor();
            String factorName = FACTOR_NAME_MAP.getOrDefault(rawFactorName, rawFactorName);
            BigDecimal weight = component.getWeight();
            BigDecimal factorValue = null;
            // 4. 根据基础因子名称获取因子值
            switch (factorName) {
                case "简单收益率因子":
                    factorValue = simpleFactor.size() > 0 ? BigDecimal.valueOf(simpleFactor.get(0)) : null;
                    break;
                case "年化收益率因子":
                    factorValue = simpleFactor.size() > 1 ? BigDecimal.valueOf(simpleFactor.get(1)) : null;
                    break;
                case "对数收益率因子":
                    factorValue = simpleFactor.size() > 2 ? BigDecimal.valueOf(simpleFactor.get(2)) : null;
                    break;
                case "波动率因子":
                    factorValue = simpleFactor.size() > 3 ? BigDecimal.valueOf(simpleFactor.get(3)) : null;
                    break;
                case "夏普比率因子":
                    factorValue = simpleFactor.size() > 4 ? BigDecimal.valueOf(simpleFactor.get(4)) : null;
                    break;
                case "最大回撤因子":
                    factorValue = simpleFactor.size() > 5 ? BigDecimal.valueOf(simpleFactor.get(5)) : null;
                    break;
                case "下行风险因子":
                    factorValue = simpleFactor.size() > 6 ? BigDecimal.valueOf(simpleFactor.get(6)) : null;
                    break;
                case "相对强弱指数因子":
                    factorValue = simpleFactor.size() > 7 ? BigDecimal.valueOf(simpleFactor.get(7)) : null;
                    break;
                case "移动平均值因子":
                    factorValue = simpleFactor.size() > 8 ? BigDecimal.valueOf(simpleFactor.get(8)) : null;
                    break;
                case "申购开放频率因子":
                    factorValue = simpleFactor.size() > 9 ? BigDecimal.valueOf(simpleFactor.get(9)) : null;
                    break;
                case "赎回开放频率因子":
                    factorValue = simpleFactor.size() > 10 ? BigDecimal.valueOf(simpleFactor.get(10)) : null;
                    break;
                default:
                    log.warn("未知的基础因子: {} (原始: {})", factorName, rawFactorName);
                    missingFactors.add(factorName + "(未知因子)");
                    continue; // 跳过未知因子
            }
            if (factorValue == null) {
                log.warn("基础因子 {} 无有效数据 [基金{}]", factorName, fundCode);
                missingFactors.add(factorName);
                continue;
            }
            
            // 根据操作类型进行计算
            try {
                switch (component.getOperationType()) {
                    case MULTIPLY:
                        if (hasValidData) {
                            result = result.multiply(factorValue).multiply(weight);
                        } else {
                            result = factorValue.multiply(weight);
                            hasValidData = true;
                        }
                        break;
                    case ADD:
                        result = result.add(factorValue.multiply(weight));
                        hasValidData = true;
                        break;
                    case DIVIDE:
                        if (factorValue.compareTo(BigDecimal.ZERO) != 0) {
                            if (hasValidData) {
                                result = result.divide(factorValue, 6, RoundingMode.HALF_UP).multiply(weight);
                            } else {
                                result = BigDecimal.ONE.divide(factorValue, 6, RoundingMode.HALF_UP).multiply(weight);
                                hasValidData = true;
                            }
                        }
                        break;
                    case SUBTRACT:
                        if (hasValidData) {
                            result = result.subtract(factorValue.multiply(weight));
                        } else {
                            result = factorValue.multiply(weight).negate();
                            hasValidData = true;
                        }
                        break;
                    case WEIGHTED_ADD:
                        if (hasValidData) {
                            result = result.add(factorValue.multiply(weight));
                        } else {
                            result = factorValue.multiply(weight);
                            hasValidData = true;
                        }
                        break;
                    case WEIGHTED_MULTIPLY:
                        if (hasValidData) {
                            result = result.multiply(factorValue).multiply(weight);
                        } else {
                            result = factorValue.multiply(weight);
                            hasValidData = true;
                        }
                        break;
                    default:
                        log.warn("未知的操作类型: {} [基金{}]", component.getOperationType(), fundCode);
                        continue;
                }
            } catch (Exception e) {
                log.error("计算错误: 因子={}, 操作={}, 值={}, 权重={}, 错误={}", 
                         factorName, component.getOperationType(), factorValue, weight, e.getMessage());
                continue;
            }
        }
        
        if (!hasValidData) {
            String msg = "没有有效的因子数据进行计算，缺失因子：" + String.join(", ", missingFactors);
            log.warn(msg);
            throw new IllegalArgumentException(msg);
        }
        
        return result;
    }

    /**
     * 根据风格类型调整计算结果
     */
    private BigDecimal applyStyleTypeAdjustment(BigDecimal value, StyleFactor.StyleType styleType) {
        switch (styleType) {
            case GROWTH:
                // 成长风格：通常关注高增长、高估值
                return value.multiply(BigDecimal.valueOf(1.1));
            case VALUE:
                // 价值风格：通常关注低估值、高股息
                return value.multiply(BigDecimal.valueOf(0.9));
            case QUALITY:
                // 质量风格：关注盈利质量、稳定性
                return value.multiply(BigDecimal.valueOf(1.05));
            case MOMENTUM:
                // 动量风格：关注价格趋势
                return value.multiply(BigDecimal.valueOf(1.15));
            case SMALL_CAP:
                // 小盘风格：关注小市值公司
                return value.multiply(BigDecimal.valueOf(1.2));
            case LARGE_CAP:
                // 大盘风格：关注大市值公司
                return value.multiply(BigDecimal.valueOf(0.95));
            default:
                return value;
        }
    }

    /**
     * 获取基金名称
     */
    private String getFundName(String fundCode) {
        // 这里应该从基金服务获取基金名称
        return "基金" + fundCode;
    }

    /**
     * 获取风格因子历史数据
     */
    @Transactional(readOnly = true)
    public StyleFactorData getStyleFactorDataById(Long styleFactorId) {
        return styleFactorDataRepository.findById(styleFactorId).orElse(null);
    }
    @Transactional(readOnly = true)
    public StyleFactorData getStyleFactorDataByFundCode(String fundCode) {
        return styleFactorDataRepository.findByFundCode(fundCode);
    }

    /**
     * 删除风格因子历史数据
     */
    public void deleteStyleFactorDataById(Long styleFactorId) {
        styleFactorDataRepository.deleteById(styleFactorId);
    }

    /**
     * 验证风格因子公式
     */
    public boolean validateFormula(String formula) {
        if (formula == null || formula.trim().isEmpty()) {
            return false;
        }

        // 简单的公式验证逻辑
        String[] operators = {"+", "-", "*", "/", "(", ")"};
        boolean hasOperator = false;

        for (String operator : operators) {
            if (formula.contains(operator)) {
                hasOperator = true;
                break;
            }
        }

        return hasOperator;
    }

    /**
     * 检查因子代码是否存在
     */
    @Transactional(readOnly = true)
    public boolean existsByFactorCode(String factorCode) {
        return styleFactorRepository.existsByFactorCode(factorCode);
    }

    /**
     * 保存风格因子计算结果
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void saveCalculationResult(String factorCode, String fundCode, BigDecimal factorValue) {
        try {
            // 查找风格因子
            Optional<StyleFactor> styleFactorOptional = styleFactorRepository.findByFactorCode(factorCode);
            if (styleFactorOptional.isEmpty()) {
                throw new IllegalArgumentException("风格因子不存在: " + factorCode);
            }
            
            StyleFactor styleFactor = styleFactorOptional.get();
            
            // 创建或更新计算结果
            StyleFactorData styleFactorData = new StyleFactorData();
            styleFactorData.setStyleFactor(styleFactor);
            styleFactorData.setFundCode(fundCode);
            styleFactorData.setCalculationDate(LocalDate.now());
            styleFactorData.setFactorValue(factorValue);
            styleFactorData.setCreateTime(LocalDateTime.now());
            
            styleFactorDataRepository.save(styleFactorData);
            
            // 更新风格因子的最后计算时间
            styleFactor.setLastCalculationTime(LocalDateTime.now());
            styleFactorRepository.save(styleFactor);
            
            log.info("成功保存风格因子计算结果: 因子={}, 基金={}, 值={}", factorCode, fundCode, factorValue);
        } catch (Exception e) {
            log.error("保存风格因子计算结果失败: 因子={}, 基金={}, 错误={}", factorCode, fundCode, e.getMessage(), e);
            throw new RuntimeException("保存计算结果失败: " + e.getMessage(), e);
        }
    }

    public boolean deleteStyleFactorById(Long id) {
        if (!styleFactorRepository.existsById(id)) {
            return false;
        }
        styleFactorRepository.deleteById(id);
        return true;
    }
}